package com.quasar.hpatient.view.personal.setup;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.quasar.hpatient.Jpush.NewWorkUtils;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.model.medicalmodel.UpdateEdition;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

//版本更新
@EActivity(R.layout.activity_up_app)
public class UpAppActivity extends BaseActivity {

    private PowerManager mPowerManager;//电源管理服务
    private android.os.PowerManager.WakeLock mWakeLock;

    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    //设置界面传过来的版本信息
    @Extra
    UpdateEdition updateEdition;
    @ViewById(R.id.info)          //新版本提示
            TextView info;
    @ViewById(R.id.submit)
    Button submit;
    @ViewById(R.id.progress)
    View progress;
    @ViewById
    ProgressBar progressBar;
    private int FileLength;
    private int DownedFileLength = 0;
    private InputStream inputStream;
    private URLConnection connection;
    private OutputStream outputStream;
    File file;

    @Click(R.id.submit)
    public void submit() {        //更新
        //更新操作0
        progress.setVisibility(View.VISIBLE);
        DownedFileLength = 0;
        submit.setEnabled(false);
        submit.setBackgroundColor(color(R.color.btpresscolor));
        // TODO Auto-generated method stub
        Thread thread = new Thread() {
            public void run() {
                try {
                    //提供的下载地址
                    DownFile(updateEdition.getDownloadurl());
                } catch (Exception e) {
                }
            }
        };
        thread.start();
    }

    private int color(int value) {
        return MainAppliaction.getInstance().getResources().getColor(value);
    }

    @AfterViews
    void init() {
        initView();
        // 电源管理服务
        mPowerManager = (PowerManager) this
                .getSystemService(Context.POWER_SERVICE);
        mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
                | PowerManager.ACQUIRE_CAUSES_WAKEUP, "S");
        mWakeLock.acquire();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWakeLock != null) {
            mWakeLock.release();
        }
    }

    @Override
    protected void initView() {
        initToolbar();
    }

    @Override
    protected void initData() {

    }

    /**
     * 网络变化之后的类型
     */
    @Override
    public void onChangeListener(int netMobile) {
        // TODO Auto-generated method stub

        if (isNetConnect()) {
            submit.setEnabled(true);
            submit.setBackgroundColor(color(R.color.colorTheme));
        }
    }

    private void DownFile(String urlString) {
        try {
            URL url = new URL(urlString);
            connection = url.openConnection();
            if (connection.getReadTimeout() == 5) {
                Log.i("---------->", "当前网络有问题");
                // return;
            }
            inputStream = connection.getInputStream();

        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        /*
         * 文件的保存路径和和文件名其中Nobody.mp3是在手机SD卡上要保存的路径，如果不存在则新建
         */
        String savePAth = Environment.getExternalStorageDirectory() + "/DownFile";
        File file1 = new File(savePAth);
        if (!file1.exists()) {
            file1.mkdir();
        }
        SimpleDateFormat dateformat2 = new SimpleDateFormat("yyyyMMdd");
        String fxx = dateformat2.format(new Date());
        String savePathString = Environment.getExternalStorageDirectory() + "/DownFile/" + fxx + "XSP.apk";
        file = new File(savePathString);
        file.deleteOnExit();

        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        /*
         * 向SD卡中写入文件,用Handle传递线程
         */
        Message message = new Message();
        try {
            outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024 * 4];
            FileLength = connection.getContentLength();
            message.what = 0;
            handler.sendMessage(message);
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
                Message message1 = new Message();
                message1.what = 1;
                handler.sendMessage(message1);
                DownedFileLength = DownedFileLength + len;
            }
            Message message2 = new Message();
            message2.what = 2;
            handler.sendMessage(message2);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {
                    case 0:
                        progressBar.setMax(FileLength);
                        progressBar.setVisibility(View.VISIBLE);
                        Log.i("文件长度----------->", progressBar.getMax() + "");
                        break;
                    case 1:
                        progressBar.setProgress(DownedFileLength);
                        int x = DownedFileLength * 100 / FileLength;
                        //textView.setText(x+"%");
                        break;
                    case 2:
                        Toast.makeText(getApplicationContext(), "下载完成", Toast.LENGTH_LONG).show();

                        UpAppActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                if (file.exists()) {
                                    Intent i = new Intent(Intent.ACTION_VIEW);
                                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    //i.setDataAndType(Uri.parse("file://" + file.toString()), "applicationnd.android.package-archive");
                                    i.setDataAndType(Uri.parse("file://" + file.toString()), "application/vnd.android.package-archive");
                                    startActivity(i);
                                }
                            }
                        });
                        break;

                    default:
                        break;
                }
            }
        }

    };

}
